<template>
  <div class="artitalk-container">
    <header class="header">
      <h1>留言区</h1>
    </header>
    <main class="main">
      <section class="main-left">
        <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="textarea"> </el-input>
      </section>
      <section class="main-right">
        <el-button type="success" @click="send">发送<i class="el-icon-s-promotion el-icon--right"></i></el-button>
      </section>
    </main>
    <footer class="footer">
      <el-card class="box-card" v-for="(item, index) in artitalk" :key="index" shadow="hover">
        <div class="item-left">
          <el-avatar shape="square" :size="50" :src="item.avatar"></el-avatar>
          <h1>{{ item.username }}</h1>
        </div>
        <div class="item-right">
          <div class="text item">
            {{ item.content }}
          </div>
          <div class="item-footer">评论时间：{{ item.created_time }}</div>
        </div>
      </el-card>
    </footer>
  </div>
</template>

<script>
export default {
  name: 'Artitalk',
  props: ['artitalks'],
  data () {
    return {
      textarea: '',
      artitalk: this.artitalks
    }
  },
  methods: {
    async send () {
      const username = localStorage.getItem('username')
      const role = localStorage.getItem('role')
      const userId = localStorage.getItem('_id')
      const avatar = localStorage.getItem('avatar')
      const content = this.textarea
      if (username) {
        const formData = {
          username,
          role,
          user_id: userId,
          avatar,
          content
        }
        const { data: res } = await this.$api.insertArtitalk(formData)
        console.log(res)
        this.artitalk = res.data
        this.textarea = ''
      } else {
        this.$notify({
          title: '警告',
          message: '登录后，才能评论。',
          type: 'warning'
        })
        setTimeout(() => {
          this.$router.replace('/')
        }, 1000)
      }
    }
  },
  watch: {
    // 非常重要，不然为空
    artitalks (newVal, oldVal) {
      this.artitalk = newVal
      for (let i = 0; i < this.artitalk.length; i++) {
        this.artitalk[i].created_time = this.$forMat(this.artitalk[i].created_time)
      }
      console.log(newVal)
    }
  }
}
</script>

<style lang="less" scoped>
.header {
  font-size: 20px;
  margin-bottom: 15px;
}
.main {
  display: flex;
  margin-bottom: 15px;
}
.main-left {
  flex: 9;
}
.main-right {
  flex: 1;
}
/deep/ .el-button--success {
  height: 100%;
}
// .footer{

// }
.text {
  font-size: 14px;
}

.box-card {
  width: 100%;
  margin-bottom: 15px;
}
/deep/ .el-card__body {
  display: flex;
  padding: 15px;
}
.item {
  padding: 0 0;
}
.item-left {
  flex: 1;
}
.item-left h1 {
  padding-left: 10px;
}
.item-right {
  position: relative;
  flex: 6;
}
.item-footer {
  // margin-top: 10px;
  position: absolute;
  bottom: 0;
  left: 0;
}
</style>
